<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="bg-container" style="justify-content: flex-end">
                <Toolbar :items="pageData.btnList" @add="addHandler" @import="importHandler" @del="deleteHandler"
                    @select="selectHandler" @export="exports" @excel="downloadHandler">
                </Toolbar>
            </div>
        </template>


        <template #pageTabel>
            <a-tabs   :lazy-load="true" :justify="true">
                <a-tab-pane>
                    <!-- <a-table style="height:100%"
                             size="mini" :scrollbar="true" sticky-header  @change="handleChange"  :draggable="{type:'handle',width:20,fixed:true}"
                             @page-change="pagination.change" stripe :bordered="true" :columns="tableColumns"
                             :row-selection="{ showCheckedAll: true, width: 50 , onlyCurrent:true}"
                             v-model:selected-keys="selectedRowKeys"
                             :loading="pageData.pageLoading" :data="table.dataList"
                             :pagination="false"
                             :rowKey="rowKey">
                        <template #action="{ record }">
                            <a-button type="primary" size="small" status="warning" @click="editHandler(record)"
                                      v-if="pageData.isEdit">
                                <template #icon>
                                    <icon-edit/>
                                </template>
                                修 改
                            </a-button>
                        </template>
                    </a-table> -->
                      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                        :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList"
                        :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
                </a-tab-pane>
            </a-tabs>
        </template>
        <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize"
            @page-size-change="change1" style="justify-content: center" :page-size="size" :current="page" />
        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label-col-flex="80px" label="名称" field="numbeName" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '名称必填' }]">
                        <a-input class="bacClass" placeholder="" v-model="dataForm.numbeName" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="针数" field="numberThreads" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '针数必填' }]">
                        <a-input-number v-model="dataForm.numberThreads" placeholder="" class="input-demo bacClass" :min="0"
                            :max="1000000000" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="寸数" field="smallNumber" :rules="[{ required: true, message: '寸数必填' }]"
                        :validate-trigger="['change', 'blur']">
                        <a-input-number v-model="dataForm.smallNumber" placeholder="" class="input-demo bacClass" :min="0"
                            :max="1000000000" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="总针数" field="totalNumberThreads" :rules="[{ required: true, message: '总针数必填' }]"
                        :validate-trigger="['change', 'blur']">
                        <a-input-number v-model="dataForm.totalNumberThreads" placeholder="" class="input-demo bacClass"
                            :min="0" :max="1000000000" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="备注" field="remark">
                        <!-- <a-input class="bacClass"  v-model="dataForm.remark"/> -->
                        <a-textarea class="bacClass" style="height:70px" placeholder="" v-model="dataForm.remark" auto-size="true" :max-length="400"
                            allow-clear show-word-limit />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>

<script lang="ts">
import { post } from "@/api/http";
import { usePagination, useRowKey, useRowSelection, useTable, useTableColumn, } from "@/hooks/table";
import emitter from '@/hooks/useEventBus'
import { onMounted, reactive, ref } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Message, Modal } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'

import {localeText} from '@/api/aggridZw'

interface ClothInfo {
    id: number | string | null;
    numberThreads: any;
    totalNumberThreads: any;
    smallNumber: any;
    deteleState: string | undefined | null;
    createName: string | undefined | null;
    createTime: string | undefined | null;
    updateName: string | undefined | null;
    updateTime: string | undefined | null;
    numbeName: any
    remark: string | undefined
}

export default {
    name: "NumberNeedles",
    setup() {
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            page.value = val
            doRefresh();
        }
        function change1(val: any) {
            size.value = val
            doRefresh();
        }
        //查询
        function doRefresh() {
            pageData.pageLoading = true
            post({
                url: "product/greyExtend/selectGreyExtendPage",
                data: {
                    page: page.value,
                    size: size.value,
                    deleteState: 0,
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        gridOption.value.setRowData(data.list)
                        table.handleSuccess(data.list);
                        total.value = data.total;

                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "名称",
                key: "numbeName",
                dataIndex: "numbeName",
                width: 150
            },
            {
                title: "针数",
                key: "numberThreads",
                dataIndex: "numberThreads",
                width: 150
            },
            {
                title: "寸数",
                key: "smallNumber",
                dataIndex: "smallNumber",
                width: 150
            },
            {
                title: "总针数",
                key: "totalNumberThreads",
                dataIndex: "totalNumberThreads",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 200
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 200
            },
            {
                title: "操作",
                key: "id",
                dataIndex: "id",
                slotName: "action",
                width: 150, fixed: 'right'
            },
        ]);
        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            pageLoading: boolean
            rHeight: any
            btnList: any[],
            isEdit: boolean
        }>({
            showAdd: false,
            sideTitle: "新增坯布针数参数",
            dropDownData: "",
            pageLoading: false,
            rHeight: "",
            btnList: [],
            isEdit: false
        });


        onMounted(() => {
            // 切换tap到本页面执行的方法
            emitter.on("NumberNeedles", () => {
                // selCxAll({});
                doRefresh();
            });
        });
        //查询
        const selectHandler = () => {
            page.value = 1
            doRefresh();
        }
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else if (key === "numberThreads" || key === "smallNumber" || key === "totalNumberThreads") {
                    dataForm[key] = 0;

                } else {
                    dataForm[key] = "";
                }
            }
            pageData.showAdd = true;
            pageData.sideTitle = "新增坯布针数参数";
        };
        const dataForm = reactive<ClothInfo>({
            id: null,
            numberThreads: "",
            smallNumber: "",
            totalNumberThreads: "",
            deteleState: "",
            createName: "",
            createTime: "",
            updateName: "",
            updateTime: "",
            numbeName: "",
            remark: ""
        });


        const gridOption = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
        }


        const formRef = ref<FormInstance>();
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    pageData.pageLoading = true;
                    if (pageData.sideTitle === "新增坯布针数参数") {
                        post({
                            url: "product/greyExtend/insert",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();

                                pageData.showAdd = false;

                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        }).finally(() => {
                            pageData.pageLoading = false
                        })
                    } else {
                        post({
                            url: "product/greyExtend/update",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;

                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        }).finally(() => {
                            pageData.pageLoading = false
                        })
                    }
                }
            });
        };
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                draggable: true,
                onOk() {
                    post({
                        url: "product/greyExtend/delete",
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id }),
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            pagination.page = 1
                            selectedRowKeys.value = [];
                            doRefresh()
                        } else {
                            Message.error({
                                content: "修改失败",
                                duration: 5000,
                            });
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                },
            });
        };
        const editHandler = (record: ClothInfo) => {
            dataForm.id = record.id;
            dataForm.numbeName = record.numbeName;
            dataForm.numberThreads = record.numberThreads;
            dataForm.totalNumberThreads = record.totalNumberThreads;
            dataForm.smallNumber = record.smallNumber;
            dataForm.remark = record.remark;
            pageData.sideTitle = '修改坯布针数参数'
            pageData.showAdd = true
        };

        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            } else {
                let idList: any = []
                gridOption.value.getSelectedRows().forEach(function (o: any) {
                    idList.push(o['id'])
                })
                //将表头拼接出来
                let head = "<th>名称</th><th>针数</th><th>寸数</th><th>总针数</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr>";
                    body += "<td>" + o["numbeName"] + "</td>";
                    body += "<td>" + o["numberThreads"] + "</td>";
                    body += "<td>" + o["smallNumber"] + "</td>";
                    body += "<td>" + o["totalNumberThreads"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '坯布针数参数', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        //模板下载
        const downloadHandler = () => {
            axios.get(baseURL + '/product/greyExtend/uploadModel', {
                responseType: 'blob',
                headers: {
                    token: sessionStorage.getItem('USER-TOKEN-KEY')
                }
            }).then((res) => {
                if (res.status === 200) {
                    filedownload(res.data, '坯布针数参数.xlsx')
                }
            })
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/greyExtend/importModelData', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()

        if (permissionStore.hasPermisson('pbzscs.cx')) {

            pageData.btnList.push("查询")
        }
        if (permissionStore.hasPermisson('pbzscs.xz')) {
            pageData.btnList.push("新增")
        }
        if (permissionStore.hasPermisson('pbzscs.sc')) {
            pageData.btnList.push("删除")
        }
        if (permissionStore.hasPermisson('pbzscs.dc')) {
            pageData.btnList.push("导出")
        }
        if (permissionStore.hasPermisson('pbzscs.dr')) {
            pageData.btnList.push("导入")
        }
        if (permissionStore.hasPermisson('pbzscs.xg')) {
            pageData.isEdit = true
        }
        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }

        let tc: any[] = tableColumns.map((o: any) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            if (o.slotName === 'action') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"

                obj['cellRenderer'] = {
                    template: `<a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
                            e: pageData.isEdit,
                            a
                        }
                    }

                }
            }

            return obj
        })

        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            // flex: 1
        }
        const localeText1:any=ref(localeText)
        return {
            localeText1,
            defaultColDef,
            tc,
            total,
            PageSize,
            change1,
            page,
            size,
            importHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            editHandler,
            selectHandler,
            exports,
            downloadHandler,
            handleChange,
            gridReady
        };
    },
    components: { Toolbar,  },
};
</script>
<style scoped lang="less">

</style>
